package com.pocket.demo.core.initializing;

import com.pocket.demo.base.system.PocketSystemInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * @author zhaozhile
 */
@Order(1)
@Component
public class PrintApplicationInfo implements PocketInitialize{

    private static final Logger LOGGER = LoggerFactory.getLogger(PrintApplicationInfo.class);

    private static final String PORT_KEY = "local.server.port";
    private static final String IP_KEY = "spring.cloud.client.ip-address";
    private static final String HOSTNAME_KEY = "spring.cloud.client.hostname";

    @Override
    public void initialize(ApplicationReadyEvent event) {

        ConfigurableEnvironment configurableEnvironment = event.getApplicationContext().getEnvironment();
        String portInt = configurableEnvironment.getProperty(PORT_KEY);
        PocketSystemInfo.serverIp = configurableEnvironment.getProperty(IP_KEY);
        PocketSystemInfo.serverPort = StringUtils.isNotBlank(portInt) ? Integer.parseInt(portInt) : null;
        PocketSystemInfo.serverHostName = configurableEnvironment.getProperty(HOSTNAME_KEY);

        if (StringUtils.isBlank(PocketSystemInfo.serverIp) || StringUtils.isBlank(PocketSystemInfo.serverHostName)){
            try {
                PocketSystemInfo.serverIp = InetAddress.getLocalHost().getHostAddress();
                PocketSystemInfo.serverHostName = InetAddress.getLocalHost().getHostName();
                LOGGER.debug("current server ip: {}, port: {}, serverHostName: {}", PocketSystemInfo.serverIp, PocketSystemInfo.serverPort, PocketSystemInfo.serverHostName);
            } catch (UnknownHostException e) {
                LOGGER.error(e.getMessage());
            }
        }
    }
}
